import React, { Component } from 'react'
import { connect } from 'dva';
import { Form, Input, Button, notification, Select, message, DatePicker, Col, Row } from 'antd';
import { FormComponentProps } from "antd/lib/form/Form";
import { DropDownSelect } from '@/components/DropDownSelect/index';
import { DICT } from '../enum';
import moment from 'moment';
import { DividerItem } from '@/components/DividerItem';

const { Option } = Select;

interface Props extends FormComponentProps {
  dispatch?: Function,
  data?: {
    id: number
  },
  keys?: Array<string>,
  dict?: any
}

@connect(({ message_content }) => ({
  dict: message_content.dict || {}
}))

class FormItem extends Component<Props, any> {
  state = {
    isNoAuto: false
  };

  componentDidMount() {
    const { data, form, dispatch } = this.props;
    if (data) {
      const { id, ...items } = data;
      form.setFieldsValue(items)
    }

    dispatch({
      type: 'message_content/queryDict',
      payload: {
        keyList: DICT
      }
    });
  }

  handleSubmit = (e) => {
    e.preventDefault();
    message.loading('', 0.5);
    const { form, data, dispatch } = this.props;
    form.validateFields((err, values) => {
      if (!err) {
        if (values.title.length > 1000) {
          message.warning('标题字符超过1000，请删减', 1.5);
          return;
        }
        if (values.content.length > 1000) {
          message.warning('内容字符超过1000，请删减内容', 1.5);
          return;
        }
        let { timingSendTime } = values;
        values.timingSendTime = timingSendTime ? moment(timingSendTime).format("YYYY-MM-DD hh:mm") : null;
        data && data.id ? dispatch({
          type: 'message_content/update',
          payload: {
            id: data.id,
            ...values
          }
        }) : dispatch({
          type: 'message_content/create',
          payload: values
        })
      } else {
        notification['error']({
          message: `${data.id ? '修改' : '新增'}失败`,
          description: '字段验证不通过',
        });
      }
    })
  };
  getOption = (data) => {
    const children = [];
    let { entries } = Object;
    for (let [key, value] of entries(data)) {
      children.push(<Option key={key}>{value}</Option>);
    }
    return children;
  };
  sendModeType = (value, data) => {
    if (data.props && data.props.children === '定时发送') {
      this.state.isNoAuto = true;
    } else {
      this.state.isNoAuto = false;
    }
  };

  render() {
    const Info = DividerItem('plus', '新增公告')
    const { form, dict } = this.props;
    const { getFieldDecorator } = form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 12 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 6 },
        sm: { span: 14 },
      },
    };

    const ButtonList = () => (
      <Form.Item>
        <Button style={{ marginLeft: 20 }} onClick={() => {
          window.history.back()
        }}>取消</Button>
        <Button type="primary"
          htmlType="submit"
          style={{ marginLeft: 20 }}
          onClick={(e: any) => {
            this.handleSubmit(e)
          }}
        >保存</Button>
      </Form.Item>
    )

    return (
      <Form>
        <Info />
        <Row style={{ minHeight: '75vh' }}>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              label="标题"
            >
              {getFieldDecorator('title', {
                rules: [{
                  required: true, message: '标题',
                }],
              })(
                <Input placeholder='请输入标题' />
              )}
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label="内容"
            >
              {getFieldDecorator('content', {
                rules: [{
                  required: true, message: '内容',
                }],
              })(
                <Input.TextArea placeholder='请输入内容' style={{ 'width': '100%', 'border': '1px solid #ddd' }} />
              )}
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label='发送方式'
            >
              {getFieldDecorator('sendMode', {
                rules: [{ required: true, message: '发布方式' }],
              })(
                <Select
                  style={{ width: '100%' }}
                  placeholder="请选择"
                  onChange={this.sendModeType}
                >
                  {dict['message.content.send.mode'] ? this.getOption(dict['message.content.send.mode']) : null}
                </Select>
              )}
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              className={this.state.isNoAuto ? '' : 'none'}
              label='定时发送时间'
            >
              {getFieldDecorator('timingSendTime', {
                rules: [{ required: true, message: '定时发送时间' }],
              })(
                <DatePicker
                  showTime
                  {...getFieldDecorator('timingSendTime')}
                  format={'YYYY/MM/DD hh:mm'}
                  style={{ width: '100%' }}
                  placeholder="请选择安装时间"
                />
              )}
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label='接收者'
            >
              {getFieldDecorator('receiveList', {
                rules: [{ required: true, message: '接收者' }],
              })(
                DropDownSelect(dict, 'user.position', 'multiple')
              )}
            </Form.Item>
          </Col>
          <Col span={12}></Col>
        </Row>
        <Row><ButtonList /></Row>
      </Form>
    );
  }
}

const FormList = Form.create()(FormItem);
export default FormList;
